<?php
/**
 * 开店星新零售管理系统
 * @description 基于Yii2+Vue2.0+uniapp研发，H5+小程序+公众号全渠道覆盖，功能完善开箱即用，框架成熟易扩展二开
 * @author 青岛开店星信息技术有限公司
 * @link https://www.kaidianxing.com
 * @copyright Copyright (c) 2020-2022 Qingdao ShopStar Information Technology Co., Ltd.
 * @copyright 版权归青岛开店星信息技术有限公司所有
 * @warning Unauthorized deletion of copyright information is prohibited.
 * @warning 未经许可禁止私自删除版权信息
 */

namespace shopstar\components\dispatch\driver;

use Matrix\Exception;
use shopstar\components\dispatch\bases\BaseDispatchDriver;
use shopstar\components\dispatch\bases\DispatchDriverInterface;
use shopstar\constants\CacheTypeConstant;
use shopstar\helpers\HttpHelper;
use shopstar\helpers\ShopUrlHelper;
use shopstar\helpers\StringHelper;
use shopstar\traits\CacheTrait;
use yii\helpers\Json;


/**
 * 码科跑腿驱动类
 * Class MakeDriver
 * @package shopstar\components\dispatch\driver
 * @author 青岛开店星信息技术有限公司
 */
class MakeDriver extends BaseDispatchDriver implements DispatchDriverInterface
{
    use CacheTrait;

    private $API_GET_TOKEN = '%s/addons/make_speed/core/public/index.php/apis/v2/get_token';

    private $API_CREATE_ORDER = '%s/addons/make_speed/core/public/index.php/apis/v2/create_order';

    private $API_ORDER_PLACE = '%s/addons/make_speed/core/public/index.php/apis/v2/get_delivery_price';

    private $API_ORDER_DETAIL = '%s/addons/make_speed/core/public/index.php/apis/v2/get_order_detail';

    private $API_VERIFY_TOKEN = '%s/addons/make_speed/core/public/index.php/apis/v2/verify_token';

    /**
     * @var string $appid appid
     */
    public $appid;

    /**
     * @var string $token token
     */
    public $token;

    /**
     * @var string $url 域名
     */
    public $url;

    /**
     * @var string $access_token access_token 请求token
     */
    private $access_token;

    public function connect()
    {
        parent::connect(); // TODO: Change the autogenerated stub

        $this->getAccessToken();

    }

    /**
     *
     * @param $data
     * @return array|mixed|null
     */
    public function addOrder($data)
    {
        $data['token'] = $this->access_token;

        return $this->send($this->API_ORDER_PLACE, $data);
    }


    /**
     * 订单提交
     * @param $data
     * @return array|mixed|null
     * @author 青岛开店星信息技术有限公司
     */
    public function orderPlace($data)
    {
        $data['token'] = $this->access_token;
        $data['notify_url'] = ShopUrlHelper::build('dispatch/notify.php', [], true);

        return $this->send($this->API_CREATE_ORDER, $data);
    }


    public function queryStatus($orderId)
    {
        $data['token'] = $this->access_token;
        $data['order_num'] = $orderId;

        return $this->send($this->API_ORDER_DETAIL, $data);
    }

    private function getAccessToken()
    {
        // 获取缓存token
        $accessToken = self::getStringCache(CacheTypeConstant::MAKE_TOKEN, [$this->appid, $this->token]);

        if (!empty($accessToken) && !$this->verifyToken($accessToken)) {
            $accessToken = '';
        }

        if (empty($accessToken)) {
            $accessTokenRes = $this->send($this->API_GET_TOKEN,
                [
                    'appid' => $this->appid,
                    'token' => $this->token
                ]
            );

            if (!isset($accessTokenRes['token']) && empty($accessTokenRes['token'])) {
                throw new Exception($accessTokenRes['message']);
            }
            $accessToken = $accessTokenRes['token'];
            // 有效期三天 缓存
            if (!empty($accessToken)) {
                self::stringCache(CacheTypeConstant::MAKE_TOKEN, $accessToken, [$this->appid, $this->token]);
            }

        }

        $this->access_token = $accessToken;
    }

    private function verifyToken($token)
    {
        $data['token'] = (string)$token;

        return $this->send($this->API_VERIFY_TOKEN, $data);
    }

    /**
     * 发送请求
     * @author 青岛开店星信息技术有限公司
     */
    private function send($url, $data)
    {

        $urlFormat = sprintf($url, $this->url);

        try {

            if ($url == $this->API_ORDER_PLACE) {

                $urlFormat .= StringHelper::exists($urlFormat, '?') ? '&' : '?';

                ksort($data);

                $queryString = '';
                foreach ($data as $key => $value) {
                    if (is_null($value)) {
                        continue;
                    } elseif (is_array($value) && empty($value)) {
                        continue;
                    }

                    $queryString .= '&' . ($key . '=' . $value);
                }
                $queryString = substr($queryString, 1);

                $response = HttpHelper::get($urlFormat . $queryString);

            } else {
                $response = HttpHelper::post($urlFormat, $data);

            }

        } catch (\Throwable $e) {

            return error('码科配送参数错误:' . $e->getMessage());
        }

        $response = Json::decode($response);

        // 授权接口直接返回
        if ($url == $this->API_GET_TOKEN) {
            return $response;
        }

        // token验证接口
        if ($url == $this->API_VERIFY_TOKEN) {
            return $response['isValid'];
        }

        if ($response['error_code'] == 0) {
            return $response['data'];
        } else {
            return error($response['msg']);
        }
    }
}